// @ts-ignore
import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios";
import {UniAdapter} from "uniapp-axios-adapter";
import {useUserStore} from "@/stores/modulers/user";
import type {JsonResult} from "@/typings/types";
import {CommonApi} from "@/api/common.api";
import config from "@/config";

const baseURL = config.baseURL;

let ElMessage = {
    error: (msg?: string) => {
        uni.showToast({
            title: msg,
            icon: "none",
            duration: 2000,
        });
    },
};

//加载配置
let requestNum: number = 0,
    loading: boolean = true;

//加载动画
const addLoading = () => {
    // 防止重复弹出
    requestNum++;
    if (requestNum == 1) {
        uni.showLoading({
            title: "加载中",
        });
    }
};

const userStore = useUserStore();
// 关闭 加载动画
const cancelLoading = () => {
    requestNum--;
    // 关闭 加载动画
    if (requestNum === 0) {
        setTimeout(() => {
            uni.hideLoading();
        }, 300);
    }
};

// @ts-ignore
export interface IceAxiosInstance extends AxiosInstance {
    get<T = any, R = AxiosResponse<T>, D = any>(
        url: string,
        config?: AxiosRequestConfig<D>
    ): Promise<JsonResult<T>>;

    post<T = any, R = AxiosResponse<T>, D = any>(
        url: string,
        data?: D,
        config?: AxiosRequestConfig<D>
    ): Promise<JsonResult<T>>;
}

//请求配置
export const createAxios = <T>(
    config?: AxiosRequestConfig
): IceAxiosInstance => {
    const instance: AxiosInstance = axios.create({
        baseURL: baseURL,
        timeout: 60 * 1000,
        adapter: UniAdapter,
        ...config,
    });
    // 添加请求拦截器
    instance.interceptors.request.use(
        function (config: any) {
            if (userStore.token) {
                config.headers["Authorization"] = "Bearer " + userStore.token;
                // config.headers["Authorization"] = "Bearer " + "1";
            }
            //加载动画
            if (loading) addLoading();
            return config;
        },
        function (error) {
            // 请求错误
            return Promise.reject(error);
        }
    );
    //refresh Token function
    let isRefreshToken = false;

    //创建响应拦截器
    instance.interceptors.response.use(
        async (response: AxiosResponse) => {
            // 关闭加载 动画
            if (loading) cancelLoading();
            //返回参数

            const JsonResult: JsonResult<any> = response.data;
            if (JsonResult.code != 0) {
                ElMessage.error(JsonResult.msg);
            }
            if (JsonResult.code == 401 && !isRefreshToken) {
                isRefreshToken = true;
                const originalRequest = response.config;
                // If the token is expired
                try {

                    return instance(originalRequest);
                } catch (e) {
                }
            }
            if (JsonResult.code == 401 && isRefreshToken) {
                isRefreshToken = false;
                ElMessage.error(JsonResult.msg);
            }
            return response.data;
        },
        async (error) => {
            // console.log("response error", error);
            // 关闭加载 动画
            if (loading) cancelLoading();
            /***** 接收到异常响应的处理开始 *****/
            if (error && error.response) {
                console.log("%cAPI", " color:#cd0a0a ", " -> error:", error);
                // 1.公共错误处理
                // 2.根据响应码具体处理
                switch (error.response.status) {
                    case 400:
                        error.message = "错误请求";
                        break;
                    case 401:
                        error.message = "未授权,请重新登录";
                        return;
                    case 403:
                        error.message = "拒绝访问";
                        break;
                    case 404:
                        error.message = "请求错误,未找到该资源";
                        break;
                    case 405:
                        error.message = "请求方法未允许";
                        break;
                    case 408:
                        error.message = "请求超时";
                        break;
                    case 500:
                        error.message = "服务器端异常";
                        break;
                    case 501:
                        error.message = "网络未实现";
                        break;
                    case 502:
                        error.message = "网络错误";
                        break;
                    case 503:
                        error.message = "服务不可用";
                        break;
                    case 504:
                        error.message = "网络超时";
                        break;
                    case 505:
                        error.message = "http版本不支持该请求";
                        break;
                    default:
                        error.message = `连接错误${error.response.status}`;
                }
            } else {
                // 超时处理
                if (JSON.stringify(error).includes("timeout")) {
                    error.message = "服务器响应超时，请刷新当前页";
                } else {
                    error.message = "连接服务器失败";
                }
            }
            //提示
            ElMessage.error(error.message);
            /***** 处理结束 *****/
            return Promise.resolve(error.response);
        }
    );

    return instance;
};
